package com.qqzone.service.impl;

import com.qqzone.dao.HostReplyDAO;
import com.qqzone.dao.ReplyDAO;
import com.qqzone.pojo.HostReply;
import com.qqzone.pojo.Reply;
import com.qqzone.pojo.Topic;
import com.qqzone.pojo.UserBasic;
import com.qqzone.service.HostReplyService;
import com.qqzone.service.ReplyService;
import com.qqzone.service.UserBasicService;

import java.util.List;

/**
 * @author Yang
 * @creat 19:02 2022/8/26
 * @sice 1.8
 */

public class ReplyServiceImpl implements ReplyService {
    private ReplyDAO replyDAO = null;

    private HostReplyService hostReplyService = null;
    private UserBasicService userBasicService = null;

    @Override
    public List<Reply> getReplyByTopicId(Integer id) {
        // 初始化 每一个Reply中，hostReply（不一定有，但是得查）
        List<Reply> replyList = replyDAO.getReplyList(new Topic(id));
        for (Reply reply : replyList) {
            HostReply hostReply = hostReplyService.getHostReplyByReplyId(reply.getId());
            UserBasic author = userBasicService.getUserBasicById(reply.getAuthor().getId());

            reply.setAuthor(author);
            reply.setHostReply(hostReply);
        }
        return replyList;
    }

    @Override
    public void addReply(Reply reply) {
        replyDAO.addReply(reply);
    }

    @Override
    public void delReply(Integer replyId) {
        // 1.根据id获取到 reply
        Reply reply = replyDAO.getReplyByReplyId(replyId);
        if(reply!=null){
            HostReply hostReply = hostReplyService.getHostReplyByReplyId(reply.getId());

            // 2.如果reply有关联的hostReply，则先删除hostReply
            if(hostReply != null){
                hostReplyService.delHostReply(hostReply.getId());
            }

            // 3.删除reply
            replyDAO.delReply(replyId);
        }
    }

    @Override
    public void delReplyList(Topic topic) {
        //  不使用 getReplyByTopicId(topic) 获取 replyList，减少了冗余查找
        // 直接使用 replyDAO.getReplyList(topic) ，不需要补充查询 author，hostReply
        // 只需要其中存在id，在遍历过程中使用的 delReply 方法内部 有对 hostReply 的查询及删除
        List<Reply> replyList = replyDAO.getReplyList(topic);
        if(replyList != null){
            // 因为这个 Topic 和 Reply 的两个表存在外键链接
            // 先删除从表，再删除主表
            for (Reply reply : replyList) {
                // replyService.delReply 删除操作里，已经有了判断主人回复并提前删除的操作。
                delReply(reply.getId());
            }
        }
    }

    @Override
    public Reply getReplyByReplyId(Integer replyId) {
        // 需要author
        Reply reply = replyDAO.getReplyByReplyId(replyId);
        UserBasic author = userBasicService.getUserBasicById(reply.getAuthor().getId());
        reply.setAuthor(author);
        return reply;
    }
}
